package com.olddriver.crm.service.impl;

import org.apache.shiro.crypto.hash.Md5Hash;
import com.olddriver.crm.domain.Employee;
import com.olddriver.crm.mapper.EmployeeMapper;
import com.olddriver.crm.page.PageResult;
import com.olddriver.crm.query.QueryObject;
import com.olddriver.crm.service.IEmployeeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Override
    public void insert(Employee employee) {
        /*对密码进行加密*/
        employee.setPassword(new Md5Hash(employee.getPassword(), employee.getUsername(), 2).toString());
        employeeMapper.insert(employee);
        if (employee.getRoles() != null) {
            employeeMapper.insertRelations(employee.getId(), employee.getRoles());
        }
    }

    @Override
    public void update(Employee employee) {
        employeeMapper.deleteRelations(employee.getId());
        employeeMapper.update(employee);
        if (employee.getRoles() != null) {
            employeeMapper.insertRelations(employee.getId(), employee.getRoles());
        }
    }

    @Override
    public void updateProfile(Employee employee) {
        employee.setPassword(new Md5Hash(employee.getPassword(), employee.getUsername(), 2).toString());
        employeeMapper.update(employee);
    }

    @Override
    public List<Employee> listAll(QueryObject qo) {
        return employeeMapper.listAll(qo);
    }

    @Override
    public PageResult query(QueryObject qo) {
        int total = employeeMapper.queryTotal(qo);
        if (total == 0) {
            return new PageResult(total, Collections.emptyList());
        }
        return new PageResult(total, employeeMapper.queryRows(qo));
    }

    @Override
    public void updateState(Boolean state, Long id) {
        employeeMapper.updateState(state, id);
    }

    public List<Employee> selectAllEmployees() {
        return employeeMapper.selectAllEmployees();
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }


}
